<?php
/**
 * @package     Joomla.Plugin
 * @subpackage  Search.contacts
 *
 * @copyright   Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Contacts Search plugin
 *
 * @package     Joomla.Plugin
 * @subpackage  Search.contacts
 * @since       1.6
 */
class PlgSearchPreposicao extends JPlugin
{
	/**
	 * Load the language file on instantiation.
	 *
	 * @var    boolean
	 * @since  3.1
	 */
	protected $autoloadLanguage = true;

	/**
	 * @return array An array of search areas
	 */
	public function onContentSearchAreas()
	{
		static $areas = array(
			'preposicao' => 'preposicao'
		);
		return $areas;
	}

	/**
	 * Contacts Search method
	 *
	 * The sql must return the following fields that are used in a common display
	 * routine: href, title, section, created, text, browsernav
	 *
	 * @param string Target search string
	 * @param string matching option, exact|any|all
	 * @param string ordering option, newest|oldest|popular|alpha|category
	 */
	public function onContentSearch($text, $phrase = '', $ordering = '', $areas = null)
	{
		$db = JFactory::getDbo();
		$app = JFactory::getApplication();
		$user = JFactory::getUser();
		$groups = implode(',', $user->getAuthorisedViewLevels());

		$searchText = $text;
		
		if (is_array($areas))
		{
			if (!array_intersect($areas, array_keys($this->onContentSearchAreas())))
			{
				return array();
			}
		}

		$sContent = $this->params->get('search_content', 1);
		$sArchived = $this->params->get('search_archived', 1);
		$limit = $this->params->def('search_limit', 50);
		$state = array();
		if ($sContent)
		{
			$state[] = 1;
		}
		if ($sArchived)
		{
			$state[] = 2;
		}

		if (empty($state))
		{
			return array();
		}

		$text = trim($text);
		if ($text == '')
		{
			return array();
		}

		$section = JText::_('PLG_SEARCH_GANESHA_PREPOSICAO');

		
		$order = 'a.titulo DESC';
		

		$text = $db->quote('%' . $db->escape($text, true) . '%', false);

		$query = $db->getQuery(true);
		//sqlsrv changes
		

		$query->select(
			'a.id, a.titulo as title, a.data as created, a.conteudo '
		);
		$query->from('#__ganeshavereadores_proposicoes AS a')
			->where(
				'(a.titulo LIKE ' . $text . ' OR a.conteudo LIKE ' . $text .')'
			)
			->order($order);
		
		
		

		$db->setQuery($query, 0, $limit);
		$rows = $db->loadObjectList();

		
		$return = array();
		if ($rows)
		{
			foreach ($rows as $key => $row)
			{
				
				$rows[$key]->href = 'index.php?option=com_ganeshavereadores&view=proposicao&id='. $row->id .'&Itemid=166';
			}

			foreach ($rows as $preposicao)
			{
				
				if (searchHelper::checkNoHTML($preposicao, $searchText, array('id', 'titulo', 'conteudo', 'url',  )))
				{
					$return[] = $preposicao;
				}
			}
		}

		return $return;
		
		
		
	}
}
